"""
AI智能报告生成服务
利用大模型生成综合性分析报告
"""
from typing import Dict, Any, List, Optional, Union
from datetime import datetime, timedelta
import json
import asyncio
from sqlalchemy.orm import Session
from sqlalchemy import func, and_, or_
import pandas as pd
import numpy as np

# from models.analysis_result import AnalysisResult, ResultStatus, PetitionData
from models.analysis_task import AnalysisTask, TaskStatus
from models.report import Report, ReportType, ReportStatus
from models.user import User
from services.llm_service import llm_service_manager
from services.geo_analysis_service import geo_analysis_service
from services.multi_dimension_analysis_service import multi_dimension_analysis_service
# from services.statistics_service import statistics_service  # 已删除统计服务
from core.logging_config import get_logger

# 日志记录器
logger = get_logger("report_generation_service")


class ReportGenerationService:
    """报告生成服务"""
    
    def __init__(self):
        self.supported_report_types = {
            "daily": "日报",
            "weekly": "周报", 
            "monthly": "月报",
            "quarterly": "季报",
            "annual": "年报",
            "custom": "自定义报告"
        }
    
    async def generate_daily_report(
        self, 
        db: Session, 
        report_date: datetime,
        user_id: int
    ) -> Dict[str, Any]:
        """生成日报"""
        logger.info(f"开始生成日报，日期: {report_date.strftime('%Y-%m-%d')}")
        
        # 获取当日数据统计
        start_date = report_date.replace(hour=0, minute=0, second=0, microsecond=0)
        end_date = start_date + timedelta(days=1)
        
        # 并行获取各种统计数据
        tasks = [
            asyncio.create_task(self._get_daily_statistics(db, start_date, end_date)),
            asyncio.create_task(self._get_daily_trends(db, start_date, end_date)),
            asyncio.create_task(self._get_daily_geo_distribution(db, start_date, end_date)),
            asyncio.create_task(self._get_daily_key_issues(db, start_date, end_date))
        ]
        
        results = await asyncio.gather(*tasks, return_exceptions=True)
        
        # 处理结果
        statistics = results[0] if not isinstance(results[0], Exception) else {}
        trends = results[1] if not isinstance(results[1], Exception) else {}
        geo_distribution = results[2] if not isinstance(results[2], Exception) else {}
        key_issues = results[3] if not isinstance(results[3], Exception) else []
        
        # 生成报告内容
        report_content = await self._generate_daily_report_content(
            report_date, statistics, trends, geo_distribution, key_issues
        )
        
        return {
            "report_type": "daily",
            "report_date": report_date.isoformat(),
            "title": f"信访分析日报 - {report_date.strftime('%Y年%m月%d日')}",
            "content": report_content,
            "statistics": statistics,
            "trends": trends,
            "geo_distribution": geo_distribution,
            "key_issues": key_issues,
            "generated_at": datetime.now().isoformat()
        }
    
    async def generate_weekly_report(
        self, 
        db: Session, 
        week_start: datetime,
        user_id: int
    ) -> Dict[str, Any]:
        """生成周报"""
        logger.info(f"开始生成周报，周开始: {week_start.strftime('%Y-%m-%d')}")
        
        week_end = week_start + timedelta(days=7)
        
        # 获取周数据统计
        tasks = [
            asyncio.create_task(self._get_weekly_statistics(db, week_start, week_end)),
            asyncio.create_task(self._get_weekly_trends(db, week_start, week_end)),
            asyncio.create_task(self._get_weekly_comparison(db, week_start, week_end)),
            asyncio.create_task(self._get_weekly_geo_analysis(db, week_start, week_end))
        ]
        
        results = await asyncio.gather(*tasks, return_exceptions=True)
        
        statistics = results[0] if not isinstance(results[0], Exception) else {}
        trends = results[1] if not isinstance(results[1], Exception) else {}
        comparison = results[2] if not isinstance(results[2], Exception) else {}
        geo_analysis = results[3] if not isinstance(results[3], Exception) else {}
        
        # 生成报告内容
        report_content = await self._generate_weekly_report_content(
            week_start, week_end, statistics, trends, comparison, geo_analysis
        )
        
        return {
            "report_type": "weekly",
            "week_start": week_start.isoformat(),
            "week_end": week_end.isoformat(),
            "title": f"信访分析周报 - {week_start.strftime('%Y年%m月%d日')}至{week_end.strftime('%Y年%m月%d日')}",
            "content": report_content,
            "statistics": statistics,
            "trends": trends,
            "comparison": comparison,
            "geo_analysis": geo_analysis,
            "generated_at": datetime.now().isoformat()
        }
    
    async def generate_monthly_report(
        self, 
        db: Session, 
        year: int,
        month: int,
        user_id: int
    ) -> Dict[str, Any]:
        """生成月报"""
        logger.info(f"开始生成月报，年月: {year}-{month}")
        
        # 计算月份起止日期
        start_date = datetime(year, month, 1)
        if month == 12:
            end_date = datetime(year + 1, 1, 1)
        else:
            end_date = datetime(year, month + 1, 1)
        
        # 获取月度数据统计
        tasks = [
            asyncio.create_task(self._get_monthly_statistics(db, start_date, end_date)),
            asyncio.create_task(self._get_monthly_trends(db, start_date, end_date)),
            asyncio.create_task(self._get_monthly_category_analysis(db, start_date, end_date)),
            asyncio.create_task(self._get_monthly_regional_analysis(db, start_date, end_date))
        ]
        
        results = await asyncio.gather(*tasks, return_exceptions=True)
        
        statistics = results[0] if not isinstance(results[0], Exception) else {}
        trends = results[1] if not isinstance(results[1], Exception) else {}
        category_analysis = results[2] if not isinstance(results[2], Exception) else {}
        regional_analysis = results[3] if not isinstance(results[3], Exception) else {}
        
        # 生成报告内容
        report_content = await self._generate_monthly_report_content(
            year, month, statistics, trends, category_analysis, regional_analysis
        )
        
        return {
            "report_type": "monthly",
            "year": year,
            "month": month,
            "start_date": start_date.isoformat(),
            "end_date": end_date.isoformat(),
            "title": f"信访分析月报 - {year}年{month}月",
            "content": report_content,
            "statistics": statistics,
            "trends": trends,
            "category_analysis": category_analysis,
            "regional_analysis": regional_analysis,
            "generated_at": datetime.now().isoformat()
        }
    
    async def generate_custom_report(
        self, 
        db: Session, 
        start_date: datetime,
        end_date: datetime,
        report_config: Dict[str, Any],
        user_id: int
    ) -> Dict[str, Any]:
        """生成自定义报告"""
        logger.info(f"开始生成自定义报告，时间范围: {start_date.strftime('%Y-%m-%d')} 至 {end_date.strftime('%Y-%m-%d')}")
        
        # 根据配置生成报告
        included_sections = report_config.get("sections", [])
        
        report_data = {
            "report_type": "custom",
            "start_date": start_date.isoformat(),
            "end_date": end_date.isoformat(),
            "title": report_config.get("title", f"自定义分析报告 - {start_date.strftime('%Y-%m-%d')}至{end_date.strftime('%Y-%m-%d')}"),
            "sections": {},
            "generated_at": datetime.now().isoformat()
        }
        
        # 根据包含的章节生成相应数据
        if "overview" in included_sections:
            report_data["sections"]["overview"] = await self._get_custom_overview(db, start_date, end_date)
        
        if "trends" in included_sections:
            report_data["sections"]["trends"] = await self._get_custom_trends(db, start_date, end_date)
        
        if "geo_analysis" in included_sections:
            report_data["sections"]["geo_analysis"] = await self._get_custom_geo_analysis(db, start_date, end_date)
        
        if "category_analysis" in included_sections:
            report_data["sections"]["category_analysis"] = await self._get_custom_category_analysis(db, start_date, end_date)
        
        if "key_issues" in included_sections:
            report_data["sections"]["key_issues"] = await self._get_custom_key_issues(db, start_date, end_date)
        
        # 生成报告内容
        report_content = await self._generate_custom_report_content(report_data, report_config)
        report_data["content"] = report_content
        
        return report_data
    
    async def _get_daily_statistics(
        self, 
        db: Session, 
        start_date: datetime, 
        end_date: datetime
    ) -> Dict[str, Any]:
        """获取日统计数据"""
        try:
            # 当日信访总数
            total_petitions = db.query(PetitionData).filter(
                and_(
                    PetitionData.created_at >= start_date,
                    PetitionData.created_at < end_date
                )
            ).count()
            
            # 按处理状态统计
            status_stats = db.query(
                PetitionData.processing_status,
                func.count(PetitionData.id).label('count')
            ).filter(
                and_(
                    PetitionData.created_at >= start_date,
                    PetitionData.created_at < end_date
                )
            ).group_by(PetitionData.processing_status).all()
            
            # 按污染类型统计
            pollution_stats = db.query(
                PetitionData.pollution_type,
                func.count(PetitionData.id).label('count')
            ).filter(
                and_(
                    PetitionData.created_at >= start_date,
                    PetitionData.created_at < end_date,
                    PetitionData.pollution_type.isnot(None)
                )
            ).group_by(PetitionData.pollution_type).all()
            
            return {
                "total_petitions": total_petitions,
                "status_distribution": [
                    {"status": stat.processing_status, "count": stat.count}
                    for stat in status_stats
                ],
                "pollution_distribution": [
                    {"type": stat.pollution_type, "count": stat.count}
                    for stat in pollution_stats
                ]
            }
        except Exception as e:
            logger.error(f"获取日统计数据失败: {str(e)}")
            return {}
    
    async def _get_daily_trends(
        self, 
        db: Session, 
        start_date: datetime, 
        end_date: datetime
    ) -> Dict[str, Any]:
        """获取日趋势数据"""
        try:
            # 按小时统计
            hourly_stats = db.query(
                func.hour(PetitionData.created_at).label('hour'),
                func.count(PetitionData.id).label('count')
            ).filter(
                and_(
                    PetitionData.created_at >= start_date,
                    PetitionData.created_at < end_date
                )
            ).group_by(func.hour(PetitionData.created_at)).all()
            
            # 填充24小时数据
            hourly_data = []
            for hour in range(24):
                count = next((stat.count for stat in hourly_stats if stat.hour == hour), 0)
                hourly_data.append({"hour": hour, "count": count})
            
            return {
                "hourly_distribution": hourly_data,
                "peak_hour": max(hourly_data, key=lambda x: x["count"])["hour"] if hourly_data else 0
            }
        except Exception as e:
            logger.error(f"获取日趋势数据失败: {str(e)}")
            return {}
    
    async def _get_daily_geo_distribution(
        self, 
        db: Session, 
        start_date: datetime, 
        end_date: datetime
    ) -> Dict[str, Any]:
        """获取日地理分布"""
        try:
            # 使用地理分析服务
            geo_data = await asyncio.to_thread(
                geo_analysis_service.get_geographic_distribution, db, None
            )
            
            # 过滤当日数据
            filtered_geo_data = {
                "province_distribution": [],
                "city_distribution": [],
                "total_count": 0
            }
            
            # 这里应该根据日期过滤，简化实现
            return geo_data
        except Exception as e:
            logger.error(f"获取日地理分布失败: {str(e)}")
            return {}
    
    async def _get_daily_key_issues(
        self, 
        db: Session, 
        start_date: datetime, 
        end_date: datetime
    ) -> List[Dict[str, Any]]:
        """获取日重点问题"""
        try:
            # 获取当日重复出现的问题
            key_issues = db.query(
                PetitionData.title,
                PetitionData.pollution_type,
                PetitionData.region,
                func.count(PetitionData.id).label('count')
            ).filter(
                and_(
                    PetitionData.created_at >= start_date,
                    PetitionData.created_at < end_date
                )
            ).group_by(
                PetitionData.title, PetitionData.pollution_type, PetitionData.region
            ).having(func.count(PetitionData.id) > 1).limit(10).all()
            
            return [
                {
                    "title": issue.title,
                    "pollution_type": issue.pollution_type,
                    "region": issue.region,
                    "frequency": issue.count
                }
                for issue in key_issues
            ]
        except Exception as e:
            logger.error(f"获取日重点问题失败: {str(e)}")
            return []
    
    async def _generate_daily_report_content(
        self, 
        report_date: datetime,
        statistics: Dict[str, Any],
        trends: Dict[str, Any],
        geo_distribution: Dict[str, Any],
        key_issues: List[Dict[str, Any]]
    ) -> str:
        """生成日报内容"""
        try:
            # 构建提示词
            prompt = f"""
            请根据以下数据生成一份信访分析日报，日期为{report_date.strftime('%Y年%m月%d日')}。

            数据统计：
            {json.dumps(statistics, ensure_ascii=False, indent=2)}

            趋势分析：
            {json.dumps(trends, ensure_ascii=False, indent=2)}

            地理分布：
            {json.dumps(geo_distribution, ensure_ascii=False, indent=2)}

            重点问题：
            {json.dumps(key_issues, ensure_ascii=False, indent=2)}

            请生成一份结构化的日报，包括：
            1. 总体情况概述
            2. 数据统计分析
            3. 趋势分析
            4. 地理分布特点
            5. 重点问题分析
            6. 建议和措施

            报告要求：
            - 语言正式、专业
            - 数据准确、分析深入
            - 重点突出、条理清晰
            - 提出切实可行的建议
            """
            
            # 调用大模型生成报告
            response = await llm_service_manager.chat_completion([
                {"role": "system", "content": "你是一个专业的信访分析专家，擅长撰写分析报告。"},
                {"role": "user", "content": prompt}
            ])
            
            return response["choices"][0]["message"]["content"]
        except Exception as e:
            logger.error(f"生成日报内容失败: {str(e)}")
            return f"日报生成失败: {str(e)}"
    
    async def _get_weekly_statistics(self, db: Session, start_date: datetime, end_date: datetime) -> Dict[str, Any]:
        """获取周统计数据"""
        try:
            # 周信访总数
            total_petitions = db.query(PetitionData).filter(
                and_(
                    PetitionData.created_at >= start_date,
                    PetitionData.created_at < end_date
                )
            ).count()
            
            # 按天统计
            daily_stats = db.query(
                func.date(PetitionData.created_at).label('date'),
                func.count(PetitionData.id).label('count')
            ).filter(
                and_(
                    PetitionData.created_at >= start_date,
                    PetitionData.created_at < end_date
                )
            ).group_by(func.date(PetitionData.created_at)).all()
            
            return {
                "total_petitions": total_petitions,
                "daily_distribution": [
                    {"date": stat.date.strftime('%Y-%m-%d'), "count": stat.count}
                    for stat in daily_stats
                ]
            }
        except Exception as e:
            logger.error(f"获取周统计数据失败: {str(e)}")
            return {}
    
    async def _get_weekly_trends(self, db: Session, start_date: datetime, end_date: datetime) -> Dict[str, Any]:
        """获取周趋势数据"""
        try:
            # 使用多维度分析服务获取趋势
            trend_data = await asyncio.to_thread(
                multi_dimension_analysis_service.get_trend_prediction, db, None, 7
            )
            
            return trend_data
        except Exception as e:
            logger.error(f"获取周趋势数据失败: {str(e)}")
            return {}
    
    async def _get_weekly_comparison(self, db: Session, start_date: datetime, end_date: datetime) -> Dict[str, Any]:
        """获取周对比数据"""
        try:
            # 与上周对比
            prev_week_start = start_date - timedelta(days=7)
            prev_week_end = end_date - timedelta(days=7)
            
            current_week_count = db.query(PetitionData).filter(
                and_(
                    PetitionData.created_at >= start_date,
                    PetitionData.created_at < end_date
                )
            ).count()
            
            prev_week_count = db.query(PetitionData).filter(
                and_(
                    PetitionData.created_at >= prev_week_start,
                    PetitionData.created_at < prev_week_end
                )
            ).count()
            
            change_rate = ((current_week_count - prev_week_count) / prev_week_count * 100) if prev_week_count > 0 else 0
            
            return {
                "current_week_count": current_week_count,
                "prev_week_count": prev_week_count,
                "change_rate": round(change_rate, 2),
                "trend": "increase" if change_rate > 0 else "decrease" if change_rate < 0 else "stable"
            }
        except Exception as e:
            logger.error(f"获取周对比数据失败: {str(e)}")
            return {}
    
    async def _get_weekly_geo_analysis(self, db: Session, start_date: datetime, end_date: datetime) -> Dict[str, Any]:
        """获取周地理分析"""
        try:
            # 使用地理分析服务
            geo_data = await asyncio.to_thread(
                geo_analysis_service.get_regional_comparison, db, None
            )
            
            return geo_data
        except Exception as e:
            logger.error(f"获取周地理分析失败: {str(e)}")
            return {}
    
    async def _generate_weekly_report_content(
        self, 
        week_start: datetime,
        week_end: datetime,
        statistics: Dict[str, Any],
        trends: Dict[str, Any],
        comparison: Dict[str, Any],
        geo_analysis: Dict[str, Any]
    ) -> str:
        """生成周报内容"""
        try:
            prompt = f"""
            请根据以下数据生成一份信访分析周报，周期为{week_start.strftime('%Y年%m月%d日')}至{week_end.strftime('%Y年%m月%d日')}。

            数据统计：
            {json.dumps(statistics, ensure_ascii=False, indent=2)}

            趋势分析：
            {json.dumps(trends, ensure_ascii=False, indent=2)}

            对比分析：
            {json.dumps(comparison, ensure_ascii=False, indent=2)}

            地理分析：
            {json.dumps(geo_analysis, ensure_ascii=False, indent=2)}

            请生成一份结构化的周报，包括：
            1. 周度总体情况
            2. 数据统计分析
            3. 趋势变化分析
            4. 同比环比分析
            5. 地理分布特点
            6. 重点问题分析
            7. 下周工作建议

            报告要求：
            - 分析全面、数据准确
            - 重点突出、条理清晰
            - 提出针对性建议
            """
            
            response = await llm_service_manager.chat_completion([
                {"role": "system", "content": "你是一个专业的信访分析专家，擅长撰写分析报告。"},
                {"role": "user", "content": prompt}
            ])
            
            return response["choices"][0]["message"]["content"]
        except Exception as e:
            logger.error(f"生成周报内容失败: {str(e)}")
            return f"周报生成失败: {str(e)}"
    
    async def _get_monthly_statistics(self, db: Session, start_date: datetime, end_date: datetime) -> Dict[str, Any]:
        """获取月统计数据"""
        try:
            # 月信访总数
            total_petitions = db.query(PetitionData).filter(
                and_(
                    PetitionData.created_at >= start_date,
                    PetitionData.created_at < end_date
                )
            ).count()
            
            # 按周统计
            weekly_stats = []
            current_date = start_date
            week_num = 1
            
            while current_date < end_date:
                week_end = min(current_date + timedelta(days=7), end_date)
                week_count = db.query(PetitionData).filter(
                    and_(
                        PetitionData.created_at >= current_date,
                        PetitionData.created_at < week_end
                    )
                ).count()
                
                weekly_stats.append({
                    "week": f"第{week_num}周",
                    "start_date": current_date.strftime('%Y-%m-%d'),
                    "end_date": week_end.strftime('%Y-%m-%d'),
                    "count": week_count
                })
                
                current_date = week_end
                week_num += 1
            
            return {
                "total_petitions": total_petitions,
                "weekly_distribution": weekly_stats
            }
        except Exception as e:
            logger.error(f"获取月统计数据失败: {str(e)}")
            return {}
    
    async def _get_monthly_trends(self, db: Session, start_date: datetime, end_date: datetime) -> Dict[str, Any]:
        """获取月趋势数据"""
        try:
            # 使用多维度分析服务
            trend_data = await asyncio.to_thread(
                multi_dimension_analysis_service.get_trend_prediction, db, None, 30
            )
            
            return trend_data
        except Exception as e:
            logger.error(f"获取月趋势数据失败: {str(e)}")
            return {}
    
    async def _get_monthly_category_analysis(self, db: Session, start_date: datetime, end_date: datetime) -> Dict[str, Any]:
        """获取月度分类分析"""
        try:
            # 使用多维度分析服务
            category_data = await asyncio.to_thread(
                multi_dimension_analysis_service.get_cross_analysis, db, None, ["pollution_type", "processing_status"]
            )
            
            return category_data
        except Exception as e:
            logger.error(f"获取月度分类分析失败: {str(e)}")
            return {}
    
    async def _get_monthly_regional_analysis(self, db: Session, start_date: datetime, end_date: datetime) -> Dict[str, Any]:
        """获取月度区域分析"""
        try:
            # 使用地理分析服务
            regional_data = await asyncio.to_thread(
                geo_analysis_service.get_regional_comparison, db, None
            )
            
            return regional_data
        except Exception as e:
            logger.error(f"获取月度区域分析失败: {str(e)}")
            return {}
    
    async def _generate_monthly_report_content(
        self, 
        year: int,
        month: int,
        statistics: Dict[str, Any],
        trends: Dict[str, Any],
        category_analysis: Dict[str, Any],
        regional_analysis: Dict[str, Any]
    ) -> str:
        """生成月报内容"""
        try:
            prompt = f"""
            请根据以下数据生成一份信访分析月报，月份为{year}年{month}月。

            数据统计：
            {json.dumps(statistics, ensure_ascii=False, indent=2)}

            趋势分析：
            {json.dumps(trends, ensure_ascii=False, indent=2)}

            分类分析：
            {json.dumps(category_analysis, ensure_ascii=False, indent=2)}

            区域分析：
            {json.dumps(regional_analysis, ensure_ascii=False, indent=2)}

            请生成一份结构化的月报，包括：
            1. 月度总体情况
            2. 数据统计分析
            3. 趋势变化分析
            4. 分类构成分析
            5. 地理分布特点
            6. 重点问题分析
            7. 工作成效评估
            8. 下月工作建议

            报告要求：
            - 分析全面、数据准确
            - 重点突出、条理清晰
            - 提出针对性建议
            """
            
            response = await llm_service_manager.chat_completion([
                {"role": "system", "content": "你是一个专业的信访分析专家，擅长撰写分析报告。"},
                {"role": "user", "content": prompt}
            ])
            
            return response["choices"][0]["message"]["content"]
        except Exception as e:
            logger.error(f"生成月报内容失败: {str(e)}")
            return f"月报生成失败: {str(e)}"
    
    async def _get_custom_overview(self, db: Session, start_date: datetime, end_date: datetime) -> Dict[str, Any]:
        """获取自定义报告概述"""
        try:
            total_petitions = db.query(PetitionData).filter(
                and_(
                    PetitionData.created_at >= start_date,
                    PetitionData.created_at < end_date
                )
            ).count()
            
            return {
                "total_petitions": total_petitions,
                "time_range": {
                    "start": start_date.strftime('%Y-%m-%d'),
                    "end": end_date.strftime('%Y-%m-%d'),
                    "days": (end_date - start_date).days
                }
            }
        except Exception as e:
            logger.error(f"获取自定义报告概述失败: {str(e)}")
            return {}
    
    async def _get_custom_trends(self, db: Session, start_date: datetime, end_date: datetime) -> Dict[str, Any]:
        """获取自定义报告趋势"""
        try:
            predict_days = (end_date - start_date).days
            trend_data = await asyncio.to_thread(
                multi_dimension_analysis_service.get_trend_prediction, db, None, predict_days
            )
            
            return trend_data
        except Exception as e:
            logger.error(f"获取自定义报告趋势失败: {str(e)}")
            return {}
    
    async def _get_custom_geo_analysis(self, db: Session, start_date: datetime, end_date: datetime) -> Dict[str, Any]:
        """获取自定义报告地理分析"""
        try:
            geo_data = await asyncio.to_thread(
                geo_analysis_service.get_geographic_distribution, db, None
            )
            
            return geo_data
        except Exception as e:
            logger.error(f"获取自定义报告地理分析失败: {str(e)}")
            return {}
    
    async def _get_custom_category_analysis(self, db: Session, start_date: datetime, end_date: datetime) -> Dict[str, Any]:
        """获取自定义报告分类分析"""
        try:
            category_data = await asyncio.to_thread(
                multi_dimension_analysis_service.get_cross_analysis, db, None, ["pollution_type", "processing_status"]
            )
            
            return category_data
        except Exception as e:
            logger.error(f"获取自定义报告分类分析失败: {str(e)}")
            return {}
    
    async def _get_custom_key_issues(self, db: Session, start_date: datetime, end_date: datetime) -> List[Dict[str, Any]]:
        """获取自定义报告重点问题"""
        try:
            key_issues = db.query(
                PetitionData.title,
                PetitionData.pollution_type,
                PetitionData.region,
                func.count(PetitionData.id).label('count')
            ).filter(
                and_(
                    PetitionData.created_at >= start_date,
                    PetitionData.created_at < end_date
                )
            ).group_by(
                PetitionData.title, PetitionData.pollution_type, PetitionData.region
            ).having(func.count(PetitionData.id) > 1).order_by(func.count(PetitionData.id).desc()).limit(20).all()
            
            return [
                {
                    "title": issue.title,
                    "pollution_type": issue.pollution_type,
                    "region": issue.region,
                    "frequency": issue.count
                }
                for issue in key_issues
            ]
        except Exception as e:
            logger.error(f"获取自定义报告重点问题失败: {str(e)}")
            return []
    
    async def _generate_custom_report_content(
        self, 
        report_data: Dict[str, Any],
        report_config: Dict[str, Any]
    ) -> str:
        """生成自定义报告内容"""
        try:
            prompt = f"""
            请根据以下数据生成一份自定义信访分析报告。

            报告配置：
            {json.dumps(report_config, ensure_ascii=False, indent=2)}

            报告数据：
            {json.dumps(report_data, ensure_ascii=False, indent=2)}

            请根据配置的报告章节生成相应的分析内容，确保：
            1. 内容符合用户需求
            2. 数据分析准确深入
            3. 重点突出、条理清晰
            4. 提出针对性建议
            """
            
            response = await llm_service_manager.chat_completion([
                {"role": "system", "content": "你是一个专业的信访分析专家，擅长撰写定制化分析报告。"},
                {"role": "user", "content": prompt}
            ])
            
            return response["choices"][0]["message"]["content"]
        except Exception as e:
            logger.error(f"生成自定义报告内容失败: {str(e)}")
            return f"自定义报告生成失败: {str(e)}"


# 创建报告生成服务实例
report_generation_service = ReportGenerationService()